<template>
  <div class="container">
    <el-card>
      <el-row>
        <el-col>
          <date-range-picker
            v-model="queryDateRange"
            :clearable="false"
            class="w-240"
            size="small"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="~"
            :start-placeholder="$t('start_date')"
            :end-placeholder="$t('end_date')"
            value-format="yyyy-MM-dd"
          />
          <el-button
            type="primary"
            icon="el-icon-search"
            size="small"
            @click="fetchAndSetupSubject"
          >
            {{ $t('search') }}
          </el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-row :gutter="20" class="p-t-15">
      <!-- 上架状态专题总数 -->
      <div class="strench-align">
        <el-col :span="24">
          <el-card class="box-card">
            <div class="thematic-detail-card">
              <div class="flex-card">
                <div>
                  <img :src="subjectContent.thumbs" class="thematic-thumb" />
                </div>
                <div>
                  <p>
                    {{ $t('topic_name') }}：{{ subjectContent.specialName }}
                    <a
                      v-if="subjectContent.status == 1"
                      :href="
                        `${SHARE_URL}/m/newSpecial/${query.id}?lan=${query.lan}`
                      "
                      class="el-button el-button--primary el-button--small"
                      target="_blank"
                    >
                      {{ $t('previews') }}
                    </a>
                    <el-button
                      v-else
                      :disabled="true"
                      type="primary"
                      size="mini"
                      >{{ $t('previews') }}</el-button
                    >
                  </p>
                  <p>
                    {{ $t('topic_language') }}：{{
                      subjectContent.lan == 'zh-Hans'
                        ? $t('chinese')
                        : $t('english_cambodian')
                    }}
                  </p>
                  <p>
                    {{ $t('content_volume') }}:
                    {{ subjectContent.contentCount }}
                  </p>
                  <p>
                    {{ $t('true_buzz_value') }}:{{ subjectContent.heatValue }}
                  </p>
                  <p>
                    {{ $t('final_heat_value') }}:
                    {{ subjectContent.showHeatValue }}
                  </p>
                  <p>{{ $t('tags') }}: {{ subjectContent.tags || $t('no') }}</p>
                  <p>
                    {{ $t('update_time') }}：{{
                      subjectContent.updateTime | msToYMDHMS
                    }}
                  </p>
                  <p>
                    {{ $t('created_time') }}：{{
                      subjectContent.createTime | msToYMDHMS
                    }}
                  </p>
                  <p>
                    {{ $t('recommended_or_not') }}：{{
                      subjectContent.isJoinRecommend
                        ? $t('recommend')
                        : $t('no')
                    }}
                  </p>
                  <p>
                    {{ $t('top_or_not') }}：{{
                      subjectContent.isTop ? $t('top') : $t('no')
                    }}
                  </p>
                  <p>
                    {{ $t('on_or_off_the_shelf') }}：{{
                      subjectContent.status == 1 ? $t('on_the_shelf') : $t('no')
                    }}
                  </p>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </div>

      <!-- 访问来源类别占比 -->
      <el-col :span="24" class="box-card">
        <el-card style="height: 100%">
          <div slot="header" class="clearfix">
            <span>{{
              $t('percentage_of_visits_to_pv_source_categories')
            }}</span>
          </div>
          <!-- 访问PV -->
          <div class="table-tab">
            <div id="rate1" :style="{ width: '100%', height: '380px' }" />
          </div>
        </el-card>
      </el-col>
    </el-row>
    <div class="box-card">
      <el-card>
        <div id="lineChart" :style="{ width: '100%', height: '480px' }" />
      </el-card>
    </div>
    <div class="box-card">
      <el-card>
        <div slot="header" class="clearfix">
          <span>{{ $t('daily_report') }}</span>
        </div>
        <div class="clearfix">
          <div class="button-list">
            <el-button @click="exportToExcel">{{ $t('export_doc') }}</el-button>
          </div>
        </div>
        <div class="list-content">
          <el-table
            v-loading="listLoading"
            id="newsTable"
            ref="newsTable"
            :data="paginationList"
            element-loading-text="Loading"
            border
            fit
            highlight-current-row
            style="width: 100%; margin-top: 20px"
            @sort-change="changeSortOrder"
          >
            <el-table-column
              v-for="header in HEADERS"
              :key="header.prop"
              :prop="header.prop"
              :label="$t(header.label)"
              sortable="true"
            />
          </el-table>
        </div>
        <div class="block fr">
          <el-pagination
            :current-page.sync="pagination.currentPage"
            :page-sizes="[20, 50, 100]"
            :page-size.sync="pagination.pageSize"
            :total="list.length"
            layout="total, sizes, prev, pager, next, jumper"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>
<script>
import { format, parse, subDays } from 'date-fns';
import echarts from 'echarts';
import { dateShortcutKeyJS } from '@/mixins/index.js';
import { exportJsonToExcel, formatJson } from '@/utils/excel/Export2Excel';
import { getSpecialSubjectDetail } from '@/api/subject.js';
import '@/assets/css/common/style.scss';

const EMPTY_QUERY = {
  beginDate: format(subDays(new Date(), 6), 'yyyy-MM-dd'),
  endDate: format(new Date(), 'yyyy-MM-dd')
};

const HEADERS = [
  { label: 'date', prop: 'date' },
  { label: 'visited_pv', prop: 'pv' },
  { label: 'visit_uv', prop: 'uv' },
  { label: 'content_read', prop: 'contentRead' },
  { label: 'exposure_read_conversions', prop: 'contentReadRate' }
];

const PV_SOURCE_MAP_LIST = [
  { value: '-1', label: 'unknown' },
  { value: '1', label: 'v1topic_clicks_h5' },
  { value: '2', label: 'v1topic_channel_entrance_clicks' },
  { value: '3', label: 'v1banner_click_hot_topic' },
  { value: '4', label: 'v1pop_up_window_click' },
  { value: '5', label: 'v1_home_recommendation_click' },
  { value: '6', label: 'v1_home_page_promotion_click' },
  {
    value: '501',
    label: 'v2_home_page_recommended_content_for_exposed_topics'
  },
  { value: '502', label: 'v2homerecommendationtopic_recommendation_module' },
  { value: '503', label: 'v2homerecommendations' },
  { value: '504', label: 'v2homefollow' },
  {
    value: '505',
    label: 'v2video_rollover_recommendation_list_of_exposed_topics'
  },
  {
    value: '506',
    label: 'v2exposed_topic_of_micro_headline_recommendation_list'
  },
  { value: '507', label: 'v2topic_detail_page_new_h5' },
  { value: '508', label: 'v2video_detail_page' },
  { value: '509', label: 'v2small_video_detail_page' },
  { value: '510', label: 'v2illustrated_detail_page' },
  { value: '511', label: 'v2gallery_detail_page' },
  { value: '512', label: 'v2micro_headlines_detail_page' },
  {
    value: '513',
    label: 'v2banner_clicks_banner_in_hot_topics_my_gold_task_list'
  },
  { value: '514', label: 'v2popup_click' },
  { value: '515', label: 'v2splash_screen_click' }
];

const PV_SOURCE_MAP = PV_SOURCE_MAP_LIST.reduce(
  (o, t) => ({ ...o, [t.value]: t.label }),
  {}
);

const CAKE_LEGEND = PV_SOURCE_MAP_LIST.map(t => t.label);

const EMPTY_PAGINATION = {
  currentPage: 1,
  pageSize: 20
};

const SORT_ORDER = ['descending', 'ascending'];

function transformDataToList(data) {
  const fields = [
    { key: 'pv', valueKey: 'count' },
    { key: 'uv', valueKey: 'count' },
    { key: 'contentRead', valueKey: 'count' },
    { key: 'contentReadRate', valueKey: 'rate' }
  ];
  if (Array.isArray(data.pv)) {
    return data.pv.map((t, index) => {
      const item = fields.reduce((o, t) => {
        const value = (data[t.key] || [])[index] || {};
        return { ...o, [t.key]: value[t.valueKey] };
      }, {});
      return { ...item, date: t.date };
    });
  }
  return [];
}

export default {
  mixins: [dateShortcutKeyJS],
  data() {
    return {
      HEADERS,
      SHARE_URL: process.env.SHARE_URL,
      sortId: HEADERS[0].prop,
      sortOrder: SORT_ORDER[0],
      query: { ...EMPTY_QUERY },
      subject: {},
      pagination: { ...EMPTY_PAGINATION },
      listLoading: false
    };
  },

  computed: {
    queryDateRange: {
      get() {
        return [this.query.beginDate, this.query.endDate];
      },
      set(value) {
        [this.query.beginDate, this.query.endDate] = value;
      }
    },

    subjectContent() {
      return this.subject.specialSubject || {};
    },

    list() {
      return transformDataToList(this.subject);
    },

    sortedList() {
      const { sortId, sortOrder } = this;
      const strToMs = s => parse(s, 'yyyy-MM-dd', new Date()).getTime();
      const makeSortMethod = getValue => swapValue => (a, b) => {
        const [x, y] = swapValue(a, b);
        return getValue(x) - getValue(y);
      };
      const makeOrderSortMethod = makeSortMethod(
        sortId === 'date' ? t => strToMs(t[sortId]) : t => parseFloat(t[sortId])
      );
      const sortMethod = makeOrderSortMethod(
        sortOrder === 'ascending' ? (a, b) => [a, b] : (a, b) => [b, a]
      );
      return this.list.slice(0).sort(sortMethod);
    },

    paginationList() {
      const { pageSize, currentPage } = this.pagination;
      const start = pageSize * (currentPage - 1);
      return this.sortedList.slice(start, start + pageSize);
    },

    pvSourceList() {
      const pvSourceList = this.subject.pvSources;
      if (!pvSourceList) return [];
      return pvSourceList.map(t => ({
        name: this.$t(PV_SOURCE_MAP[t.source]),
        value: t.count
      }));
    }
  },

  watch: {
    list() {
      this.$nextTick(() => {
        this.updateLineChart();
        this.updateCakeChart();
      });
    }
  },

  created() {
    this.query = {
      ...this.query,
      ...this.$pick(['lan', 'id'])(this.$route.query)
    };
    this.fetchAndSetupSubject();
  },

  methods: {
    async fetchSubject(options = {}) {
      try {
        this.listLoading = true;
        const params = { ...this.query, ...options };
        const res = await getSpecialSubjectDetail(params);
        if (res.code === 200) {
          return res.data;
        }
        const msg = res.msg || res.data;
        this.$message({ type: 'error', message: msg });
        throw new Error(msg);
      } finally {
        this.listLoading = false;
      }
    },

    async fetchAndSetupSubject(options = {}) {
      const data = await this.fetchSubject(options);
      this.subject = data;
    },

    changeSortOrder({ prop, order }) {
      this.sortOrder = order;
      this.sortId = prop;
    },

    /* pv图表 */
    updateCakeChart() {
      const myChart = echarts.init(document.getElementById('rate1'));
      myChart.showLoading();

      const option = {
        color: this.$store.state.app.eChartColor,
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          data: CAKE_LEGEND.map(label => this.$t(label))
        },
        series: [
          {
            name: this.$t('visit_uv'),
            type: 'pie',
            radius: ['40%', '55%'],
            data: this.pvSourceList
          }
        ]
      };
      myChart.setOption(option, true);
      myChart.hideLoading();
    },

    /* 拆线图 */
    updateLineChart() {
      const myChart = echarts.init(document.getElementById('lineChart'));
      myChart.showLoading();

      const makePickList = fn => k =>
        this.subject[k] ? this.subject[k].map(t => fn(t)) : [];
      const pickCountList = makePickList(t => t.count);
      const pickDateList = makePickList(t => t.date);

      const option = {
        title: {
          text: this.$t('data_trends')
        },
        color: this.$store.state.app.eChartColor,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: [
            this.$t('visited_pv'),
            this.$t('visit_uv'),
            this.$t('topic_content_read'),
            this.$t('exposure_read_conversions')
          ],
          right: 60,
          top: 10
        },
        grid: {
          left: 60,
          right: 60
        },
        xAxis: [{ type: 'category', data: pickDateList('pv') }],
        yAxis: [
          {
            type: 'value',
            name: `(${this.$t('number_of_times')})`,
            axisLabel: { formatter: '{value}' }
          },
          {
            type: 'value',
            name: `(${this.$t('percentage')})`,
            axisLabel: { formatter: '{value}' }
          }
        ],
        series: [
          {
            name: this.$t('visited_pv'),
            type: 'line',
            data: pickCountList('pv')
          },
          {
            name: this.$t('visit_uv'),
            type: 'line',
            data: pickCountList('uv')
          },
          {
            name: `(${this.$t('topic_content_read')})`,
            type: 'line',
            data: pickCountList('contentRead')
          },
          {
            name: `(${this.$t('exposure_read_conversions')})`,
            type: 'line',
            data: pickCountList('contentReadRateNumber'),
            yAxisIndex: 1
          }
        ]
      };

      myChart.setOption(option, true);
      myChart.hideLoading();
    },

    // 复制成功
    onCopySuccess() {
      this.$message({
        message: this.$t('replication_success'),
        type: 'success'
      });
    },

    // 复制失败
    onCopyError() {
      this.$message({
        message: this.$t('copy_failure'),
        type: 'error'
      });
    },

    async exportToExcel() {
      const headers = HEADERS.map(t => this.$t(t.label));
      const props = HEADERS.map(t => t.prop);
      const lan =
        this.query.lan === 'zh-Hans'
          ? this.$t('chinese')
          : this.$t('english_cambodian');
      const name = this.subjectContent.specialName;
      const filename = `${lan}${this.$t('special_page')}-${name}-${
        this.query.beginDate
      }~${this.query.endDate}`;
      exportJsonToExcel(headers, formatJson(props, this.list), filename);
    }
  }
};
</script>
<style lang="scss" scoped>
.w-150 {
  width: 150px;
}
/* 标签盒子 */
.box-card {
  margin: 0 0 20px 0;
}
.thematic-detail-card {
  .flex-card {
    display: flex;
    line-height: 32px;
    .thematic-thumb {
      margin-right: 20px;
      width: 340px;
      height: auto;
    }
  }
}
/* 表格tab */
.button-list {
  float: right;
}
.list-content {
  overflow: hidden;
}
.block {
  margin: 20px 0 0 0;
}

.strench-align {
  display: flex;
  align-items: strench;
}
</style>
